package com.leyou.auth.service.impl;


import com.leyou.auth.constants.RedisConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;

import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;


import com.leyou.common.utils.CookieUtils;
import com.leyou.item.dto.UserDTO;
import com.leyou.user.clients.UserClients;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl implements UserAuthService {

    @Autowired
    private UserClients userClients;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;

    //用户登录授权
    @Override
    public void userLoginAuthorization(String username, String password, HttpServletResponse response) {
        String token = null;

        try {
            //先请求User服务进行用户效验
            UserDTO userDTO = userClients.queryUserByUsernamePassword(username, password);
            if (userDTO == null) {
                throw new LyException("用户信息输入错误", 400);
            }
            //UserDTO转换为UserDetail
            UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());

            //用户校验成功生成toke
            token = jwtUtils.createJwt(userDetail);
        } catch (FeignException e) {
            //Feign远程调用异常
            throw new LyException(e.getMessage(), e.status());
        }

        //生成cookie返回给客服端
        Cookie cookie = new Cookie("KY_TOKEN", token);

        // cookie的作用域,只要游览器的根路径是leyou.com(后缀,一级域名)就会携带cookie
        cookie.setDomain("leyou.com");

        // cookie作用的路径，/代表一切路径
        cookie.setPath("/");

        // 是否禁止JS操作cookie，避免XSS攻击
        cookie.setHttpOnly(true);

        // cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
        cookie.setMaxAge(-1);

        //发送cookie
        response.addCookie(cookie);

    }



    // 用户退出登录
    @Override
    public void userLoginOut(HttpServletRequest request, HttpServletResponse response) {
        //Redis有Jti就删除，没有不用抛异常，要的就是没有
        try {
            //获取cookie中的token
            String token = CookieUtils.getCookieValue(request, "KY_TOKEN");
            //删除Redis中的jti
            Payload payload = jwtUtils.parseJwt(token);
            //Redis中存储Jti的key
            String redisJtiKey = RedisConstants.JTI_KEY_PREFIX + payload.getUserDetail().getId();

            redisTemplate.delete(redisJtiKey);
        } catch (Exception e) {
        }

        //生成空白cookie返回客服端覆盖原来的cookie,
        Cookie cookie = new Cookie("KY_TOKEN", "");

        // cookie的作用域,只要游览器的根路径是leyou.com(后缀,一级域名)就会携带cookie
        cookie.setDomain("leyou.com");

        // cookie作用的路径，/代表一切路径
        cookie.setPath("/");

        // cookie有效期 0
        cookie.setMaxAge(0);

        //发送cookie
        response.addCookie(cookie);

    }
}
